﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OfficeOpenXml;
using OfficeOpenXml.Drawing.Chart;
using OfficeOpenXml.Style;

namespace read2imu
{
    internal class Excell
    {
        /// <summary>
        /// 导入excel
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="data"></param>
        public void WriteExcel_Table(string FileName, DataTable data)
        {
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
            ExcelPackage package = new ExcelPackage();
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("原始数据");
            int rowindex = 1;
            int colindex = 1;
            for (int i = 0; i < data.Columns.Count; i++)
            {
                worksheet.Cells[rowindex, colindex + i].Value = data.Columns[i].ColumnName;
                worksheet.Cells[rowindex, colindex + i].Style.Font.Name = "宋体";
                worksheet.Cells[rowindex, colindex + i].Style.Font.Bold = false;
                worksheet.Cells[rowindex, colindex + i].Style.Font.Size = 10;
                worksheet.Column(colindex + i).AutoFit();
            }
            rowindex++;
            for (int i = 0; i < data.Rows.Count; i++)
            {
                for (int j = 0; j < data.Columns.Count; j++)
                {
                    worksheet.Cells[rowindex + i, colindex + j].Value = data.Rows[i][j];
                }
                worksheet.Row(rowindex + i).CustomHeight = true;
            }
            worksheet.Cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
            worksheet.Cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
            worksheet.Cells.Style.WrapText = false;
            worksheet.Cells.Style.ShrinkToFit = true;
            worksheet.View.FreezePanes(2, 1);
            FileStream filestream = new FileStream(FileName, FileMode.Create);
            package.SaveAs(filestream);

            filestream.Close();
            filestream.Dispose();
            worksheet.Dispose();
            package.Dispose();
            GC.Collect();
        }
    }
}
